﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Reflection;
public class ReflectSingleton<T>
{
    private static T instance;

    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                Type t = typeof(T);
                ConstructorInfo[] cInfos = t.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);
                foreach (ConstructorInfo info in cInfos)
                {
                    ParameterInfo[] pInfos = info.GetParameters();
                    if (pInfos.Length == 0)
                    {
                        instance = (T)info.Invoke(null);
                        break;
                    }
                }
                if (instance == null)
                {
                    throw new NotSupportedException("没有私有的无参构造函数（不是单例）");
                    Debug.LogError("没有私有的无参构造函数（不是单例）");
                }
            }return instance;
        }
    }
    public static T GetInstance()
    {
        Type t = typeof(T);
        ConstructorInfo[] cInfos = t.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);
        ConstructorInfo ctor = Array.Find(cInfos, (cInfo) => { return cInfo.GetParameters().Length == 0; });
        if (ctor != null)
        {
            instance = (T)ctor.Invoke(null);
        }
        else
        {
            throw new NotSupportedException("没有私有的无参构造函数（不是单例）");
        }
        return instance;
    }
}
